<?php
/**
 *
 * User: konakona http://www.crazyphper.com
 * Date: 13-5-22
 * Time: 下午8:26
 */
class OrderModel extends CommonModel
{
	/**
	 * 日期方式
	 * 周、月、日
	 * @var
	 */
	protected $dateType;
	/**
	 * 日期范围
	 * 除了日，一般是范围
	 * @var
	 */
	protected $dateVal;


	/**
	 * 日期查询的sql条件
	 * @var string
	 */
	protected $timeSql = '';

	/**
	 * 根据GET传递的值，决定是用月、周、日获得数据
	 */
	private function _getDateVal()
	{
		switch ($_GET['type'])
		{
            default:
			case 'thisweek':
				$this->timeSql = " DATE_FORMAT( FROM_UNIXTIME(add_time), '%Y%m%u' ) = DATE_FORMAT( CURDATE() , '%Y%m%u' ) ";
				break;
			case 'lastweek':
				break;
			case 'thismonth':
				$this->timeSql = " DATE_FORMAT( FROM_UNIXTIME(add_time), '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' ) ";
				break;
			case 'lastmonth':
				$this->timeSql = " PERIOD_DIFF( date_format( now() , '%Y%m' ) , date_format( FROM_UNIXTIME(add_time), '%Y%m' ) ) =1 ";
				break;
		}
	}


	/**
	 * 查看分店销量
	 * 如果指定了分店id，则如此，否则显示所有店铺的总销量！
	 */
	private function _getBossID()
	{
		if ($_SESSION['loginBossID']  > 0)
		{
			$this->bossWhere =' boss_id = '.$_SESSION['loginBossID'];
		}
	}

	/**
	 * 获得所有分类的大饼
	 */
	public function  getBig()
	{
		$this->_getDateVal();
		$this->_getBossID();

		$saleResult = array();

		$cartModel = M('shop_cart'); //购物车模型

		//获得所有商品分类
		$cateArr = M('ShopCate')->select();

		$map = array();

		$total = 0;

		foreach ($cateArr as $k => $v)
		{
			$whereSql = " type = 1 AND cate_id = {$v['id']} AND " . ($this->timeSql ? $this->timeSql : "") .($this->bossWhere ? " AND ".$this->bossWhere : "");
			//获得商品下的销量……
			$tempResult = $cartModel->field('num,id,order_id')->where($whereSql)->select();

			//销量默认为0，避免js出错
			$saleResult[$k]['num'] = 0;

			//通过循环获得销量总值
			if ($tempResult) foreach ($tempResult as $tk => $tv)
			{
				//确认订单状态为真才算成功销量
				if ($this->where(array('id' => $tv['order_id'], 'status' => 1))->count() > 0)
				{
					$saleResult[$k]['num'] += $tv['num'];
				}
			}

			//数组获得分类名
			$saleResult[$k]['name'] = $v['name'];

			$total += $saleResult[$k]['num'];

			unset($tempResult);
		}
//再次循环，计算百分比...
			foreach($saleResult as $k=>$v){
//				数量÷总数×100=百分比
				$saleResult[$k]['percentage'] = round(($v['num'] / $total) * 100,2);
			}
		return $saleResult;

	}

    /**
     * 将所有的未读记录修改为已读
     */
    public function allHaveRead(){
        $this->where(array('read_type'=>0))->save(array('read_type'=>1));
    }
}
